package org.budo.phone.rongying;

import org.budo.phone.api.AbstractPhoneApi;
import org.budo.support.http.client.Request;
import org.budo.support.http.client.Response;
import org.budo.support.lang.util.MapUtil;
import org.budo.support.lang.util.StringUtil;
import org.budo.time.Time;
import org.springframework.util.Base64Utils;
import org.springframework.util.DigestUtils;

import com.alibaba.fastjson.JSON;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 */
@Getter
@Setter
@Slf4j
public  class AbstractRongyingPhoneApi extends AbstractPhoneApi {
    /**
     * 坐席账号
     */
    private static final String VOIP_ACCOUNT = "80446100000004";

    private String restUrl = "https://wdapi.yuntongxin.vip";

    private String accountSid;

    private String appId;
    
    private String appToken;

    /**
     * http://wd.yuntongxin.vip/html/product-y-used1.html
     */
    // @Override
    public void dial(String phone) {
        String now = Time.now().toString("yyyyMMddHHmmss");

        String str1 = this.getAccountSid() + ":" + this.getAppId() + ":" + now;
        String sig = DigestUtils.md5DigestAsHex(StringUtil.getUtf8Bytes(str1)).toUpperCase();

        String str2 = this.getAppId() + ":" + this.getAppToken()+ ":" + now;
        String authorization = Base64Utils.encodeToString(StringUtil.getUtf8Bytes(str2));

        String url = this.getRestUrl() + "/bind/callEvent/v2?Sig=" + sig;
        Request request = new Request();
        request.setUrl(url);
        request.setMethod(Request.POST);

        request.setHeader("Accept", "application/json");
        request.setHeader("Content-Type", "application/json;charset=utf-8");
        request.setHeader("Authorization", authorization);

        request.setRequestBody(JSON.toJSONString(MapUtil.stringMap("Appid", this.getAppId(), //
                "Phone", phone, //
                "voipAccount", VOIP_ACCOUNT)));

        Response response = request.execute();

        log.info("#22 response=" + response + ", request=" + request);
    }
}